package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class login_filter implements Filter
{
	private FilterConfig filter_config;

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException
	{
		// TODO Auto-generated method stub
		
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		HttpSession session = request.getSession();
		
		
		//获取不过滤的地址
		String nofilterPath = filter_config.getInitParameter("nofilterPath");
		if(nofilterPath != null)
		{
			String[] pathArr = nofilterPath.split(";");
			for(int i = 0; i < pathArr.length; i++)
			{
				//字符串为空，做下一轮处理
				if(pathArr[i] == null || "".equals(pathArr[i])) continue;

				if(request.getRequestURI().indexOf(pathArr[i]) != -1)
				{
					//放行
					arg2.doFilter(arg0, arg1);
					return;
				}
			}
		}
		
		//修改字符集，可以防止后台中文乱码
		String charset = filter_config.getInitParameter("charset");
		if(charset == null)
		{
			charset = "UTF-8";
		}
		request.setCharacterEncoding(charset);
		
		
		//session有值
		if(session.getAttribute("username") != null)
		{
			//放行
			arg2.doFilter(arg0, arg1);
		}
		else
		{
			response.sendRedirect("login.jsp");
		}
	
	}

	@Override
	public void destroy()
	{
		// TODO Auto-generated method stub
		Filter.super.destroy();
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException
	{
		// TODO Auto-generated method stub
		filter_config = filterConfig;
	}

}
